package controllers;

import java.util.ArrayList;
import java.util.List;

import models.User;
import play.Logger;
import play.Play;
import play.mvc.Scope.Session;
import utils.constants.SessionConstants;

public class Security extends Secure.Security {
	// MAIN ROLES
	public static final String USER_ROLE = "USER_ROLE";
	public static final String ADMIN_ROLE = "ADMIN_ROLE";
	
	// SPECIFIC APPLICATION ROLES
	public static final String BLUEHAT_ROLE = "BLUEHAT_ROLE";
	public static final String PARTICIPANT_ROLE = "PARTICIPANT_ROLE";
	
	public static final String[] ROLES = {USER_ROLE, ADMIN_ROLE, BLUEHAT_ROLE, PARTICIPANT_ROLE};
	
	static boolean authenticate(String username, String password) {
		Logger.debug("Authenticate -- always return false because there isn't username and password authentication");
		return false;
	}
	
	static boolean check(String role) {
    	Logger.debug("Checking Role: %s", role);
    	
    	try {
    		User user = getCurrentUser();
    		Logger.debug("User: %s", user != null ? user.getProfile().getEmail() : "Unknown!!!");
    		if(user != null) {
	    		if(USER_ROLE.equals(role)) {
	    			return user.hasAccess();
	        		//return true; // TODO Check if this assumption is ok
	        	} else if(ADMIN_ROLE.equals(role)) {
	                return user.getProfile().isManager();
	            } else {
	            	if(user.getRoles().contains(role)) return true;
	            	else return false;
	            }
    		}
    	} catch(Exception e) {
    		Logger.error(e.getMessage());
    		return false;
    	}

        return false;
    }
	
	static void onCheckFailed() {
		User user = getCurrentUser();
		if(user != null && user.getRoles() != null &&  user.getRoles().size() == 0) {
			forbidden("Your organization manager must give you your roles.");
		} else {
			forbidden();
		}
	}
	
	static User getCurrentUser() {
		
		User user = User.getById(Session.current().get(SessionConstants.USER));
		if(user != null) {
    		return user;
		} else {
			return null;
		}
	}
	
	static List<String> getRoles() {
		ArrayList<String> roles = new ArrayList<String>();
		roles.add(BLUEHAT_ROLE);
		roles.add(PARTICIPANT_ROLE);
		return roles;
	}
}
